package com.huaxin.hxcloud.work;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.SignInfoDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.find.view.adapter.ImagePickerAdapter;
import com.huaxin.hxcloud.work.event.HxIsRefreshEventBus;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author songxf
 *         created at 2017/7/13 17:32
 * @desc 签到-->描述
 */

public class HxSignDesActivity extends BaseActivity implements ImagePickerAdapter.OnDeleteItemClickListener, ImagePickerAdapter.OnRecyclerViewItemClickListener {
    private static final String TAG = "HxSignDesActivity";
    @BindView(R.id.more)
    TextView     mMore;
    @BindView(R.id.toolbar)
    Toolbar      mToolbar;
    @BindView(R.id.type_recyclerview)
    RecyclerView mTypeRecyclerview;
    @BindView(R.id.picker_recyclerview)
    RecyclerView mPickerRecyclerview;
    @BindView(R.id.des_et)
    EditText     mDesEt;
    private HxMatterRecycleAdapter mAdapter;

    //选中数量限制
    private int maxImgCount = 3;
    //当前选择的所有图片
    private ArrayList<ImageItem> mSelImageList;
    public static final int IMAGE_ITEM_ADD       = -1;
    public static final int REQUEST_CODE_SELECT  = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private ImagePickerAdapter              mImagePickerAdapter;
    private List<SignInfoDTO.SignTypesBean> mSignTypes;
    private List<String>                    mMatters;
    private int                             mSignId;
    private int                             mType;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_sign_des;
    }

    @Override
    public void initView() {
        mMore.setText("提交");
        mToolbar.setTitle("添加描述");

        ImagePicker picker = BaseApp.getImagePicker();
        if (picker != null) {
            picker.setSelectLimit(maxImgCount);
        }
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        mSignTypes = intent.getParcelableArrayListExtra("SIGN_TYPES");
        mSignId = intent.getIntExtra("SIGN_ID", -1);
        mType = intent.getIntExtra("TYPE", -1);


        mTypeRecyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        mTypeRecyclerview.setHasFixedSize(true);

        mAdapter = new HxMatterRecycleAdapter(this, mSignTypes);
        mTypeRecyclerview.setAdapter(mAdapter);
        mAdapter.setItemOnClickListener(new HxMatterRecycleAdapter.OnItemClickListener() {
            @Override
            public void OnItemClickListener(List<String> matters) {
                Log.d(TAG, "onClickListener: ----->" + matters);
                ToastUtil.showToast(matters + "");
                mMatters = matters;
            }
        });

        mSelImageList = new ArrayList<>();
        mImagePickerAdapter = new ImagePickerAdapter(this, mSelImageList, maxImgCount);
        mImagePickerAdapter.setDeleteItemClickListener(this);
        mImagePickerAdapter.setOnItemClickListener(this);
        mPickerRecyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        mPickerRecyclerview.setHasFixedSize(true);
        mPickerRecyclerview.setAdapter(mImagePickerAdapter);
    }

    @OnClick({R.id.more, R.id.toolbar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.more:
              //  ToastUtil.showToast("提交");
                submitForm();
                break;
           case R.id.toolbar:
                finish();
                break;
        }
    }


    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    mSelImageList.addAll(images);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    mSelImageList.clear();
                    mSelImageList.addAll(images);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }
        }
    }

    @Override
    public void onDeleteItemClick(int position) {
        if (mSelImageList.size() > 0) {
            mSelImageList.remove(position);
            mImagePickerAdapter.setImages(mSelImageList);
        }
    }


    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - mSelImageList.size());
                Intent intent1 = new Intent(HxSignDesActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
                //                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) mImagePickerAdapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    /**
     * @desc 提交表单
     * @author songxf
     * created at 2017/7/17 10:24
     * 接口 addSignInfo
     * signId 整形
     * file 文件
     * typeIds 字符串
     * des 字符串
     */
    public void submitForm() {
        String desEd = mDesEt.getText().toString();
        if (TextUtils.isEmpty(desEd) && mSelImageList.size() == 0 && mMatters == null) {
            ToastUtil.showToast("没有内容");
            return;
        }
        //图片路径集合
        List<String> imageDatas = new ArrayList<>();

        for (int i = 0; i < mSelImageList.size(); i++) {
            String path = mSelImageList.get(i).path;
            imageDatas.add(path);
        }
        final ProgressDialog dialog = DialogUtil.getWaitDialog(this, "提交中...");
        dialog.show();
        Log.d(TAG, "--描述内容-->" + desEd);
        Log.d(TAG, "--图片路径-->" + imageDatas);
        Log.d(TAG, "--mSignId-->" + mSignId);

        Log.d(TAG, "--mMatters-->" + listDecan(mMatters));
        Log.d(TAG, "--type-->" + mType);

        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().commitAddSignIfo(mSignId, RequestHelper.createFileParts(imageDatas.toArray(new String[imageDatas.size()]))
                , listDecan(mMatters), desEd, mType);
        Log.d(TAG, "submitForm: --->" + call.request().url());
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                dialog.dismiss();
                if (response.isSuccessful()) {
                    if (baseDTO != null && baseDTO.getState() > 0) {
                        ToastUtil.showToast(getString(R.string.submit_success));
                        EventBus.getDefault().post(new HxIsRefreshEventBus(true));
                        finish();
                    } else {
                        ToastUtil.showToast(getString(R.string.submit_faile));
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.submit_faile));
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast(getString(R.string.network_faile));
            }
        });
    }

    /**
     * @desc 去掉 list 中括号
     * @author songxf
     * created at 2017/7/26 17:54
     */
    private String listDecan(List<String> str) {
        if (str==null || str.size()==0){
            return null;
        }
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < str.size(); i++) {
            strBuilder.append(str.get(i) + ",");
        }
        return strBuilder.substring(0, strBuilder.length() - 1);

    }
}
